package cn.edu.scau.cmi.ema.service;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.domain.Eventpunish;
import cn.edu.scau.cmi.ema.domain.Punish;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;
@Service("PunishService")
@Transactional

public class PunishServiceImpl extends CmiEmaService implements PunishService {
	public PunishServiceImpl() {
	}

	@Transactional
	public Punish savePunish(Punish punish) {
		Set<Eventpunish> existingEventpunishsForPunish = new HashSet<Eventpunish>();

		Set<Eventpunish> selectedEventpunishsForPunish = punish.getEventpunishsForPunish();

		if (punish.getId() == null) {

			Punish existingPunish = punishDAO.findPunishByPhysicalPrimaryKey(punish.getName());

			if (isEquals(punish, existingPunish)) {
				return existingPunish;
			}

			punish = punishDAO.store(punish);
			punishDAO.flush();

			for (Eventpunish relatedEventpunish : selectedEventpunishsForPunish) {
				relatedEventpunish.setPunish(punish);
				eventpunishDAO.store(relatedEventpunish);
			}
		} else {
			Punish existingPunish = punishDAO.findPunishByPrimaryKey(punish.getId());

			existingEventpunishsForPunish = existingPunish.getEventpunishsForPunish();

			Set<Eventpunish> prepareDeleteEventpunishsForPunish = new HashSet<Eventpunish>();
			Set<Eventpunish> prepareAddEventpunishsForPunish = new HashSet<Eventpunish>();

			prepareDeleteEventpunishsForPunish.addAll(selectedEventpunishsForPunish);
			prepareDeleteEventpunishsForPunish.addAll(existingEventpunishsForPunish);

			prepareAddEventpunishsForPunish.addAll(selectedEventpunishsForPunish);
			prepareAddEventpunishsForPunish.addAll(existingEventpunishsForPunish);

			prepareDeleteEventpunishsForPunish.removeAll(selectedEventpunishsForPunish);
			prepareAddEventpunishsForPunish.removeAll(existingEventpunishsForPunish);

			for (Eventpunish relatedEventpunish : prepareAddEventpunishsForPunish) {
				relatedEventpunish.setPunish(punish);
				eventpunishDAO.store(relatedEventpunish);
			}

			for (Eventpunish relatedEventpunish : prepareDeleteEventpunishsForPunish) {
				relatedEventpunish.setPunish(null);
				eventpunishDAO.store(relatedEventpunish);
			}
			punish = punishDAO.store(punish);
			punishDAO.flush();
		}

		eventpunishDAO.flush();
		return punish;
	}

	public void deletePunish(Punish punish) {
		punishDAO.remove(punish);
		punishDAO.flush();
	}

	@Transactional
	public void deletePunishs(Set<Integer> deletePunishsId) {
		Query query = punishDAO.createNamedQuery("deletePunishsById", -1, -1);
		query.setParameter(1, deletePunishsId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Punish> loadPunishs() {
		return punishDAO.findAllPunishs();

	}

	@Transactional
	public Set<Punish> loadReferencePunishs(Set<Punish> punishs) {
		Iterator<Punish> punishsIterator = punishs.iterator();
		Set<Punish> referencedPunishs = new HashSet<>();
		while (punishsIterator.hasNext()) {
			Punish currentPunish = punishsIterator.next();

			if (!currentPunish.getEventpunishsForPunish().isEmpty()) {
				referencedPunishs.add(currentPunish);
				continue;
			}
		}
		return referencedPunishs;
	}

	public Set<Punish> loadPunishsByIdSet(Set<Integer> punishIdSet) {

		Iterator<Integer> punishIdIterator = punishIdSet.iterator();
		Set<Punish> punishSet = new HashSet<>();
		while (punishIdIterator.hasNext()) {
			Integer id = punishIdIterator.next();
			Punish currentPunish = punishDAO.findPunishById(id);
			punishSet.add(currentPunish);
		}
		return punishSet;
	}

	@Transactional
	public List<Punish> findAllPunishs(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Punish>(punishDAO.findAllPunishs(startResult, maxRows));
	}

	@Transactional
	public Punish findPunishByPrimaryKey(Integer id) {
		return punishDAO.findPunishByPrimaryKey(id);
	}

	@Transactional
	public Integer countPunishs() {
		return ((Long) punishDAO.createQuerySingleResult("select count(o) from Punish o").getSingleResult()).intValue();
	}

	@Transactional
	public Integer countPunishs(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Punish.class);
		return ((Long) punishDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 *
	 */
	@Transactional
	public Integer countPunishsByName(String queryName) {
		Query query = punishDAO.createNamedQuery("countPunishsByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countPunishsByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Punish.class);
		Session session = (Session) entityManager.getDelegate();
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadPunishObjectReferencedSet(Punish punish) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> eventpunishsIds = new HashSet<Integer>();
		for (Eventpunish obj : punish.getEventpunishsForPunish()) {

			eventpunishsIds.add(obj.getId());
		}
		objectReferencedSetMap.put("eventpunishsIds", eventpunishsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadPunishClassReferencedSet(Punish punish) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("eventpunishs", eventpunishDAO.findAllEventpunishs());

		return classReferencedSetMap;
	}

	public boolean isEquals(Punish punish, Object obj) {
		if (obj == punish)
			return true;
		if (!(obj instanceof Punish))
			return false;
		Punish comparedPunish = (Punish) obj;
		if (!CheckPropertyEqual(punish.getName(), comparedPunish.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

